package com.nd.aspectj;

import cn.hutool.core.date.DateTime;
import com.nd.dao.JurisdictionMapper;
import com.nd.dao.LogMapper;
import com.nd.pojo.bean.Admin;
import com.nd.pojo.bean.Jurisdiction;
import com.nd.pojo.bean.JurisdictionExample;
import com.nd.pojo.bean.Log;
import com.nd.pojo.vo.BaseRespVo;
import com.nd.pojo.vo.ErrorAndErrno;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Field;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * @program: project2mall
 * @description: 对于 管理模块数据的封装
 * @author: shit_code_builder
 * @create: 2021-06-04 22:53
 **/

@Component
@Aspect
public class AopMsg <T>{

    @Autowired
    JurisdictionMapper jurisdictionMapper;

    @Autowired
    LogMapper logMapper;

    @Pointcut("execution(public com.nd.pojo.vo.ErrorAndErrno com.nd.service..*(..))")
    public void errmsgAnderrno() {
    }

    @Around("errmsgAnderrno()")
    public ErrorAndErrno aroundLog(ProceedingJoinPoint point) throws Throwable {
        ErrorAndErrno errorAndErrno = new ErrorAndErrno<>();
        try {
            ErrorAndErrno proceed = (ErrorAndErrno)point.proceed();
            proceed.setErrmsg("成功");
            proceed.setErrno(0);
            errorAndErrno=proceed;
        }catch (Exception e){
            String string = e.toString();
            errorAndErrno.setErrno(500);
            errorAndErrno.setErrmsg(string);
        }

        return errorAndErrno;
    }

    @Pointcut("execution(public com.nd.pojo.vo.BaseRespVo com.nd.controller..*(..))")
    public void log() {
    }


    @Around("log()")
    public BaseRespVo<T> methodAfterReturning(ProceedingJoinPoint point) throws Throwable {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes)RequestContextHolder.currentRequestAttributes();
        HttpServletRequest request = Objects.requireNonNull(requestAttributes).getRequest();
        String ip = request.getRemoteAddr();//地址
        String requestURI = request.getRequestURI();

        BaseRespVo result = (BaseRespVo)point.proceed();

        if (requestURI.equals("/admin/auth/login")||requestURI.equals("/admin/auth/logout")){
        return result;

        }else{
         Subject subject = SecurityUtils.getSubject();
        Admin principal = (Admin) subject.getPrincipal();
         Date lastLoginTime = principal.getLastLoginTime();
         String username = principal.getUsername();
            DateTime now = DateTime.now();//添加修改时间
            String errmsg = "";//result
            Integer type = 1;

            try {
                errmsg =result.getErrmsg();//result
            } catch (Exception e) {
                e.printStackTrace();
            }
            Boolean status = null;
            if ("成功".equals(errmsg)){ status=true; }else { status=false;}


            JurisdictionExample example = new JurisdictionExample();
            example.createCriteria().andApiLike("%"+requestURI+"%");

            List<Jurisdiction> jurisdictions = jurisdictionMapper.selectByExample(example);
            String action="";
            for (Jurisdiction jurisdiction : jurisdictions) {
                String pid = jurisdiction.getPid();
                String label= jurisdiction.getLabel();
                action += pid+label+"\n";
            }
            if ("".equals(action))action=requestURI;

            Log build = Log.builder().action(action).addTime(lastLoginTime).updateTime(now).admin(username)
                    .ip(ip).type(type).status(status).result(errmsg).comment("").deleted(false).build();
            logMapper.insert(build);
            return result;
        }


    }


//    @AfterReturning(value = "log()",returning = "result")
//    public BaseRespVo<T> methodAfterReturning(BaseRespVo<T> result)  {
//        ServletRequestAttributes requestAttributes = (ServletRequestAttributes)RequestContextHolder.currentRequestAttributes();
//        HttpServletRequest request = Objects.requireNonNull(requestAttributes).getRequest();
//        String ip = request.getRemoteAddr();//地址
//        Subject subject = SecurityUtils.getSubject();
//        Admin principal = (Admin) subject.getPrincipal();
//        Date lastLoginTime = principal.getLastLoginTime();
//        String username = principal.getUsername();
//
////        String adminName = (String)request.getSession().getAttribute("adminName");//用户名
////        Date addtime = (Date) request.getSession().getAttribute("addTime");
//        DateTime now = DateTime.now();//添加修改时间
//        String errmsg = "";//result
//        Integer type = 1;
//
//        try {
//           errmsg =result.getErrmsg();//result
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        Boolean status = null;
//        if ("成功".equals(errmsg)){ status=true; }else { status=false;}
//        String requestURI = request.getRequestURI();
//
//        JurisdictionExample example = new JurisdictionExample();
//        example.createCriteria().andApiLike("%"+requestURI+"%");
//
//        List<Jurisdiction> jurisdictions = jurisdictionMapper.selectByExample(example);
//        String action="";
//        for (Jurisdiction jurisdiction : jurisdictions) {
//            String pid = jurisdiction.getPid();
//            String label= jurisdiction.getLabel();
//            action += pid+label+"\n";
//        }
//        if ("".equals(action))action=requestURI;
//
//        Log build = Log.builder().action(action).addTime(lastLoginTime).updateTime(now).admin(username)
//                .ip(ip).type(type).status(status).result(errmsg).comment("").deleted(false).build();
//        logMapper.insert(build);
//        return result;
//    }




}
